package com.tywj.panda.driver.service

import android.app.ActivityManager
import android.app.Service
import android.content.Intent
import android.os.Binder
import android.os.IBinder
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.location.AMapLocationListener
import com.tywj.lib.core.common.util.LogUtil
import com.tywj.lib.core.common.util.ToastUtil.shortToast
import com.tywj.panda.customer.common.R
import com.tywj.panda.customer.common.http.PDStringCallback
import com.tywj.panda.customer.common.tool.LogoutTool
import com.tywj.panda.driver.api.DriverApi
import com.tywj.panda.driver.entity.DriverTaskEntity
import com.tywj.panda.driver.event.DriverEvent
import com.tywj.panda.driver.more.DriverMoreTaskActivity
import java.util.*

/**
 * <pre>
 *     author : June Yang
 *     time   : 2020/7/8
 *     desc   :  启动后台上传坐标服务
 *     version: 2.0.0
 * </pre>
 */
class GPSLocationService : Service() {

    companion object {
        const val PARAMS_BEAN = "uploadBean"
        const val PARAMS_WORK_StATUS = "work_Status"
        const val STATUS_START_TYPE = 1
        const val STATUS_END_TYPE = 2
    }


    private var uploadBean: DriverTaskEntity.DataBean? = null


    private var workStatus = STATUS_START_TYPE

    private var isStart = false
    private var isEnd = false



    //后台上传坐标放到这里
    private var mLocationClient: AMapLocationClient? = null

    //多次启动也只会调用一次
    override fun onCreate() {
        super.onCreate()
        LogUtil.d("service--onCreate")
    }

    //bindService 才有的方法
    override fun onBind(intent: Intent?): IBinder? {
        LogUtil.d("service--onBind")
        return Binder()
    }

    //startService每一次服务启动都会调用一次，一般的逻辑代码都写在这里
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        LogUtil.d("service--onStartCommand")
        //获取传递的数据
        uploadBean = intent?.getParcelableExtra(PARAMS_BEAN)

        //打卡状态 开始打卡或结束打卡
        workStatus = intent?.getIntExtra(PARAMS_WORK_StATUS, STATUS_START_TYPE)!!

        uploadBean?.let {
            getLocation(it, workStatus)
        }

        return START_STICKY;
    }

    /**
     * https://lbs.amap.com/api/android-location-sdk/guide/android-location/getlocation
     */
    private fun getLocation(bean: DriverTaskEntity.DataBean, workStatus: Int) {
        //声明定位回调监听器
        val mLocationListener = AMapLocationListener { aMapLocation ->
            if (aMapLocation != null) {
                if (aMapLocation.errorCode == 0) {
                    //定位成功回调信息，设置相关消息
                    LogUtil.i("location success,lat = ${aMapLocation.latitude} lon = ${aMapLocation.longitude}当前地址:${aMapLocation.address}")
                    //经度
                    val list = ArrayList<Double>()
                    list.add(aMapLocation.longitude)
                    list.add(aMapLocation.latitude)
                    uploadAddress(list, aMapLocation.address, bean, workStatus)
                } else {

                    //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                    LogUtil.e(
                        "location fail, ErrCode:"
                                + aMapLocation.errorCode + ", errInfo:"
                                + aMapLocation.errorInfo
                    )
                    if (aMapLocation.errorCode == 12) {
                        shortToast("定位失败，请在设置中打开GPS定位权限")
                    } else {
                        shortToast(aMapLocation.errorInfo)
                    }
                }
            }
        }
        //初始化定位
        if (mLocationClient == null) {
            mLocationClient = AMapLocationClient(this)
        }
        //设置定位回调监听
        mLocationClient?.setLocationListener(mLocationListener)

        val mLocationOption = getDefaultOption()
        mLocationClient?.setLocationOption(mLocationOption)
        //启动定位 在使用定位SDK时，请尽量保证网络畅通，如获取网络定位，地址信息等都需要设备可以正常接入网络。
        mLocationClient?.startLocation()
    }

    override fun onDestroy() {
        super.onDestroy()
        LogUtil.d("service-- onDestroy")
        //停止定位后，本地定位服务并不会被销毁
        mLocationClient?.stopLocation()
        //销毁定位客户端，同时销毁本地定位服务。
        mLocationClient?.onDestroy()
    }

    private fun uploadAddress(
        listLoc: ArrayList<Double>,
        address: String,
        bean: DriverTaskEntity.DataBean,
        workStatus: Int
    ) {
        DriverApi.saveAddress(locList = listLoc, addressName = address, bean = bean, workStatus = workStatus)
            .execute(object : PDStringCallback() {
                override fun success(message: String) {
                    LogUtil.d("upload driver pos success")
                    //第一次获取成功，刷新列表
                    // 结束打卡 刷新列表
                    if (workStatus == STATUS_START_TYPE && !isStart) {
                        isStart = true
                        LogUtil.d("start refresh")
                        DriverEvent.refreshTaskEvent.post(Unit)
                        shortToast("开始打卡成功")
                        return
                    }

                    if (workStatus == STATUS_END_TYPE && !isEnd) {
                        isEnd = true
                        DriverEvent.refreshTaskEvent.post(Unit)
                        shortToast("结束打卡成功")
                        //销毁时会消息传递失败
//                        stopSelf()
                        LogUtil.d("end refresh and stop service")
                    }
                }

                override fun error(code: Int, message: String) {
                    super.error(code, message)
                    LogUtil.d("upload driver pos fail:code=$code,$message")

                    when (code) {
                        -4, 401 -> {
                            LogoutTool.logout(R.string.common_account_login_token_is_expired)
                            stopSelf()
                        }
                    }
                }
            })
    }

    private fun getDefaultOption(): AMapLocationClientOption {
        val mOption = AMapLocationClientOption()
        //高精度定位模式：会同时使用网络定位和GPS定位，优先返回最高精度的定位结果，以及对应的地址描述信息。
        mOption.locationMode = AMapLocationClientOption.AMapLocationMode.Hight_Accuracy
        mOption.isOnceLocation = false
        //是否获取地址
        mOption.isNeedAddress = true
        //每间隔15秒钟定位一次
        mOption.interval = 15_000
//        启用缓存策略，SDK将在设备位置未改变时返回之前相同位置的缓存结果
        mOption.isLocationCacheEnable = true
        mOption.httpTimeOut = 10_000

        return mOption
    }

    private var mListener: IRefresh? = null

    fun setRefreshEvent(listener: IRefresh) {
        mListener = listener
    }

    interface IRefresh {
        fun refresh()
    }
}